import axios from "axios";
import { ElMessage } from "element-plus";

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // 设置默认的基础 URL
  timeout: 5000, // 设置超时时间
  headers: { "X-Requested-With": "XMLHttpRequest" },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // console.log("config", config);
    if (config.url === "/api/user/login") {
      return config;
    }
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // console.log("response", response);
    if (response.status !== 200) {
      ElMessage.error("服务端错误! 状态码: " + response.status);
      return Promise.reject(new Error("服务端错误!"));
    } else {
      // 处理响应数据
      if (response.data.code === 7402) {
        ElMessage.error("登录已过期，请重新登录~");
        localStorage.removeItem("token");
        window.location.href = "/login";
        return Promise.reject(new Error("登录已过期，请重新登录~"));
      }
      return response.data;
    }
  },
  (error) => {
    // console.log(error);
    ElMessage.error("请求失败，请检查网络或重试~ code:" + error.message);
    return Promise.reject(error);
  }
);

export default service;
